<template>
  <div id="threeBox" ></div>
</template>

<script>
import * as THREE from "three";
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'
export default {
name: "basic2",
data() {
  return {
  }
},

methods: {
  OrbitControls,
  init() {
    // 获取让其宽高相等
    let w = document.getElementById("threeBox").offsetWidth;
    let h = document.getElementById("threeBox").offsetHeight;
    
  //  场景
    let scene = new THREE.Scene()
    // 相机
    const camera = new THREE.PerspectiveCamera( 75, w / h, 0.1, 1000 ); //视角 宽高比 近截面远截面
    // 渲染器元素
    const renderer = new THREE.WebGLRenderer({
      alpha: true, // 背景是否可以设置透明色
      antialias: true, // 表示是否开启反锯齿
    });
    renderer.setSize( w, h ); //渲染器大小
    document.getElementById("threeBox").appendChild( renderer.domElement ); //放到body里 
    // 创建模型
    let geometry = new THREE.BoxGeometry(1,1,1) //几何体尺寸设置
    let material = new THREE.MeshBasicMaterial({
      color:0x00ff00,//颜色
      transparent:true,
      opacity:0.5
    }) //材质 : 网格默认材质
    let cube = new THREE.Mesh(geometry,material)//创建网格 把大小和材质放进去

    // 把几何体放进场景
    scene.add(cube)

    // 设置相机位置 两种方式
    camera.position.x = 5
    camera.position.y = 5
    camera.position.z = 5
    // camera.position.set(0,0,10)
    
    camera.lookAt(0,0,0)  //相机原点位置

    //世界坐标辅助器
    let axesHelper = new THREE.AxesHelper(5) 
    scene.add(axesHelper)

    // 轨道控制器
    let OrbitControls = new this.OrbitControls(camera,document.getElementById("threeBox")) //相机 监听内容
    OrbitControls.autoRotate = true //自动旋转
    OrbitControls.autoRotateSpeed = 2 //自动旋转 越大越快
    OrbitControls.enableDamping = true //阻尼
    OrbitControls.dampingFactor = 1 //阻尼 越小阻尼越小

    
    const gridHelper = new THREE.GridHelper(10,10); //设置辅助网格
    scene.add(gridHelper)

    function an(){
      // 更新轨道控制器
      OrbitControls.update()
      // 重复渲染
      requestAnimationFrame(an)
      // cube.rotation.x += 0.01
      // cube.rotation.y += 0.01
      
      renderer.render(scene,camera)
    }
    //渲染一次先
    an()
  },
},

watch: {},
computed: {},

created() {},
mounted() {
  this.init();
},
beforeDestroy() {
},
};
</script>

<style scoped lang="less">
#threeBox{
  width:400px;
 height: 400px; 
}
</style>